﻿//using Aspose.Words;
using Microsoft.Extensions.Configuration;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            FunctionsAssemblyResolver.RedirectAssembly();

            var builder = new ConfigurationBuilder()
                .SetBasePath(/*AppDomain.CurrentDomain.BaseDirectory*/Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            var Configuration = builder.Build();

            var _basePath = Configuration["Data:BaseFile"];
            var _tempPath = Configuration["Data:TemplateFileName"] + ".docx";


            if (string.IsNullOrWhiteSpace(_basePath))
            {
                _basePath = Directory.GetCurrentDirectory();
                Line("未配置程序工作目录，将使用下列位置作为程序工作目录：\n" + _basePath + "\n", ConsoleColor.Red);
            }
            if (!Directory.Exists(_basePath))
            {
                _basePath = Directory.GetCurrentDirectory();
                Line("配置程序工作目录错误，将使用下列位置作为程序工作目录：\n" + _basePath + "\n",ConsoleColor.Red);
            }
            _tempPath = Path.Combine(_basePath, _tempPath);
            if (!File.Exists(_tempPath))
            {
                Line("未找到模板文件：\n" + _tempPath + "\n",ConsoleColor.Red);
            }

            var service = new NPOIService();
            try
            {
            ReceiveFileName:
                Line("请输入要转换的 Excel 文档名称（不带路径和后缀的文件名）：\n", ConsoleColor.Green);

                var xlsPath = Path.Combine(_basePath, Console.ReadLine() + ".xlsx");
                if (!File.Exists(xlsPath))
                {
                    Line("错误，文件不存在或文件不有效的 .xlsx 格式文档\n",ConsoleColor.Red);
                    goto ReceiveFileName;
                }

                Console.WriteLine($"开始读取\n {xlsPath} \n");

                var xls = service.ReadXLSX(xlsPath);

                if (!xls.Success)
                {
                    Line($"读取文件 \n {xlsPath}  错误：\n",ConsoleColor.Red);

                    foreach (var item in xls.Errors)
                    {
                        Line($"错误位置：第 {item.y} 行, 第 {item.y} 列\t位置原因：{item.ErrorInfo}",ConsoleColor.Red);
                    }

                    Console.WriteLine("请按任意键退出程序...\n");
                    Console.ReadKey();
                    return;
                }

                Console.WriteLine($"已读取到数据 {xls.Data.Count - 1} 行, {xls.Data.First().Count()} 列\n");

                Console.WriteLine("正在转换...\n");
                service.ReadTemp(xls.Data, _tempPath, Path.GetFileNameWithoutExtension(xlsPath));
                Console.WriteLine("转换成功\n");

                Console.WriteLine("正合并文档...\n");

                using (var wordService = new WordService())
                {
                    var path = Path.Combine(_basePath, Path.GetFileNameWithoutExtension(xlsPath));
                    if (Directory.Exists(path))
                    {
                        var docx = Directory.GetFiles(path, "*.docx").OrderBy(s => int.Parse(Regex.Match(s, @"\d+").Value)).ToList();
                        if (docx.Count > 1)
                        {
                            var allDocPath = Path.Combine(path, "all.docx");
                            wordService.CreateEmptyTempDoc(docx.First(), allDocPath);
                            wordService.InsertMerge(allDocPath, docx, allDocPath);
                        }
                        else
                        {
                            Console.WriteLine("文档数量为1，无需合并\n");
                        }
                    }
                }

                Console.WriteLine("合并文档成功...\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"出现错误：{ex.Message}");
            }

            Console.WriteLine("请按任意键退出程序...\n");
            Console.ReadKey();
        }

        public static void Line(string text, ConsoleColor colour = ConsoleColor.White)
        {
            var originalColour = Console.ForegroundColor;
            Console.ForegroundColor = colour;
            Console.WriteLine(text);
            Console.ForegroundColor = originalColour;
        }

    }
    public class FunctionsAssemblyResolver
    {
        public static void RedirectAssembly()
        {
            //预加载一下所有的引用程序集
            List<string> list = AppDomain.CurrentDomain.GetAssemblies().OrderByDescending(a => a.FullName).Select(a => a.FullName).ToList();
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }

        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var requestedAssembly = new AssemblyName(args.Name);
            Assembly assembly = null;
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
            try
            {
                assembly = Assembly.Load(requestedAssembly.Name);
            }
            catch
            {
                // ignored
            }

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            return assembly;
        }
    }

}
